﻿using System.Reflection;

namespace SuperX.Common.Code
{
    public class CodeObject
    {
        public string Name { get; set; }

        public IProject Project { get; private set; }

        public CodeObject(IProject project, string name)
        {
            Name = name;
            Project = project;
        }

        public IBasicObject GetObject(string fullName)
        {
            if (Project == null)
                return null;
            if (Project.Objects.ContainsKey(fullName))
            {
                return Project.Objects[fullName];
            }
            return null;
        }

        public object GetPropertyValue(string fullName, string propertyName)
        {
            var obj = GetObject(fullName);
            return obj?.GetPropertyValue(propertyName);
        }

        public bool SetPropertyValue(string fullName, string propertyName, object value)
        {
            var obj = GetObject(fullName);
            return obj?.SetPropertyValue(propertyName, value) ?? false;
        }

        public object Invoke(string fullName, string methodName, params object[] parameters)
        {
            var obj = GetObject(fullName);
            if (obj == null)
            {
                return null;
            }
            var type = obj.GetType();
            var methodInfo = type.GetMethod(methodName, BindingFlags.CreateInstance | BindingFlags.Public);
            return methodInfo == null ? null : methodInfo.Invoke(obj, parameters);
        }
    }
}